package com.neusoft.neuiotms.dcom.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityNotFoundException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.converter.TeamGroupConverter;
import com.neusoft.neuiotms.dcom.dto.TeamGroupDTO;
import com.neusoft.neuiotms.dcom.dto.UserDutyInfoDTO;
import com.neusoft.neuiotms.dcom.model.TeamGroup;
import com.neusoft.neuiotms.dcom.model.TeamUser;
import com.neusoft.neuiotms.dcom.repository.TeamGroupRepository;
import com.neusoft.neuiotms.dcom.repository.TeamUserRepository;
import com.neusoft.neuiotms.dcom.service.TeamGroupService;

@Service
public class TeamGroupServiceImpl implements TeamGroupService {

    @Autowired
    private TeamGroupConverter teamGroupConverter;
    @Autowired
    private TeamGroupRepository teamGroupRepository;
    @Autowired
    private TeamUserRepository teamUserRepository;

    @Override
    public List<TeamGroupDTO> index(final Searchable searchable) {

        final List<TeamGroup> models = this.teamGroupRepository.index(searchable);
        return this.teamGroupConverter.toListDTO(models);
    }

    @Override
    public Page<TeamGroupDTO> search(final Pageable pageable, final Searchable searchable) {

        final Page<TeamGroup> result = this.teamGroupRepository.search(pageable, searchable);
        return this.teamGroupConverter.toPageDTO(result);
    }

    @Override
    public TeamGroupDTO create(final TeamGroupDTO dto) {

        // 校验每个人只能在一个组
        final List<String> errorList = new ArrayList<>();
        dto.getUsers().stream().map(k -> {
            final TeamUser user = this.teamUserRepository.findByCode(k.getCode());
            if (null != user) {
                return user.getName();
            } else {
                return null;
            }
        }).filter(s -> null != s).forEach(errorList::add);

        if (!errorList.isEmpty()) {
            final StringBuilder b = new StringBuilder();
            errorList.stream().forEach(k -> {
                b.append(k + " ");
            });
            throw new UnitedException("[" + b.toString() + "]这些人员已经存在别的组");
        }

        final TeamGroup model = this.teamGroupConverter.toModel(dto);
        this.teamGroupRepository.save(model);

        return this.teamGroupConverter.toDTO(model);
    }

    @Override
    public TeamGroupDTO update(final Long id, final TeamGroupDTO dto) {

        // 校验每个人只能在一个职能组
        final List<String> errorList = new ArrayList<>();
        dto.getUsers().stream().map(k -> {
            final TeamUser user = this.teamUserRepository.findByCode(k.getCode());
            if ((null != user) && (user.getGroup().getId().longValue() != id.longValue())) {
                return user.getName();
            } else {
                return null;
            }
        }).filter(s -> null != s).forEach(errorList::add);

        if (!errorList.isEmpty()) {
            final StringBuilder b = new StringBuilder();
            errorList.stream().forEach(k -> {
                b.append(k + " ");
            });
            throw new UnitedException("[" + b.toString() + "]这些人员已经存在别的组");
        }

        TeamGroup model;

        try {
            model = this.teamGroupRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        dto.setId(model.getId());
        model = this.teamGroupConverter.toModel(dto);
        this.teamGroupRepository.save(model);

        return this.teamGroupConverter.toDTO(model);
    }

    @Override
    public TeamGroupDTO details(final Long id) {

        TeamGroup model;

        try {
            model = this.teamGroupRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        return this.teamGroupConverter.toDTO(model);
    }

    @Override
    public void delete(final Long id) {

        try {
            this.teamGroupRepository.deleteById(id);
        } catch (final Exception e) {
            throw new UnitedException("次小组已经安排了排班，不能删除");
        }
    }

    @Override
    public List<UserDutyInfoDTO> dutyInfo(final UserBean user) {

        final Searchable searchable = new Searchable();
        searchable.put("userName", user.getUsername());
        final List<TeamGroup> models = this.teamGroupRepository.index(searchable);
        return this.teamGroupConverter.toListBean(models, user);
    }

}
